package com.caption.core.handler;
import com.caption.core.constant.InterfaceDefine;
import com.caption.core.executor.WorkExecutorManager;
import com.caption.core.process.Process;
import com.caption.core.process.ProcessAdapter;
import com.caption.core.result.TCRequest;
import com.caption.core.result.TCResponse;
import com.caption.utils.ApplicationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 分发器
 */
@Component
@Slf4j
public class DispatcherManager {
    @Autowired
    private WorkExecutorManager workExecutorManager;

    public TCResponse handle(TCRequest request) {
        String interfaceId = request.getInterfaceId();
        String beanId = InterfaceDefine.interfaceMap.get(interfaceId);
        String workExecutorName = InterfaceDefine.processMap.get(beanId);
        Process process = ApplicationUtils.getBean(beanId);
        Future<TCResponse> future = (Future) workExecutorManager.submit(workExecutorName, new ProcessAdapter(process, request));
        TCResponse tcResponse = null;
        try {
            tcResponse = future.get(120, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            tcResponse  = new TCResponse(request.getInterfaceId(),request.getSerialNo(),500,"线程中断异常",null);
        } catch (ExecutionException e) {
            tcResponse  = new TCResponse(request.getInterfaceId(),request.getSerialNo(),500,e.getMessage(),null);
        } catch (TimeoutException e) {
            tcResponse  = new TCResponse(request.getInterfaceId(),request.getSerialNo(),400,"请求接口超时",null);
            log.info("执行任务超时 interfaceId:{},serialNo:{}",request.getInterfaceId(),request.getSerialNo());
        }
        return tcResponse;
    }

}
